package atom.core3.j2ee.privilege;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import atom.core0.util.StringUtil;
import atom.core2.j2ee.bean.LoginedResource;
import atom.core2.j2ee.util.RequestManager;
import atom.core2.j2ee.util.WebResource;
import atom.core3.j2ee.privilege.bean.LoginSessionInfo;
import atom.core3.j2ee.util.URLMatchUtils;

/**
 * 用户登录过滤
 * 
 * @author aps-zmc
 * 
 */
public class PrivilegeFilter extends HttpServlet implements Filter
{

	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(PrivilegeFilter.class);
	private FilterConfig filterConfig;
	private static final String FILTER_FILE="conf/springconf/bean/global-resource-filter.xml";
	private static final String ERROR_URL = "/pages_public/common/error.jsp";
	private static final String OVERTIME_URL = "/pages_public/common/overtime.jsp";
	private static final String NO_PRIVILEGE_URL = "/pages_public/common/no_privilege.jsp";
	private static String[] PUBLIC_URLS ;
	private LoginSessionInfo sessionInfo;

	protected LoginSessionInfo isLogin(HttpServletRequest request,String uri) 
	{
		return null;
	}
	protected LoginSessionInfo isLogin(HttpServletRequest request) 
	{
		return null;
	}


	/**
   	 * 登陆后的公用资源
   	 */
   	private static String[] LOGINED_PUBLIC_URLS ;	

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
	{
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		try
		{

			String uri = WebResource.getURI(request);
			String apppath = request.getContextPath();
/////////////
			if (isPublicUri(uri))
			{
				// 是否已登录.获取SSO中的Object
				sessionInfo =  isLogin(request);
				if (sessionInfo!=null) 
				{
					request.setAttribute("session_info", sessionInfo);
					request.setAttribute("ssosession", sessionInfo.getSSOObject());
				}				
				filterChain.doFilter(servletRequest, servletResponse);
				return;
			}
			else
			{
				// 是否已登录.获取SSO中的Object
				sessionInfo =  isLogin(request,apppath+uri);
				if (sessionInfo==null) 
				{
					//后台跳转 不再请求了 地址栏不变
					RequestManager.forward(request, response, OVERTIME_URL);
					return;
				}
				else
				{
					request.setAttribute("session_info", sessionInfo);
					request.setAttribute("ssosession", sessionInfo.getSSOObject());
				}
			}
////////////////			
			// 是否已登录.
			/*
			sessionInfo =  isLogin(request,apppath+uri);
			if (sessionInfo==null) 
			{
				// 公共资源.
				//把判断公共资源放在稍后的目的是为了，获取SSO中的Object
				if (isPublicUri(uri))
				{
					filterChain.doFilter(servletRequest, servletResponse);
					return;
				}
				//这是页面浏览器跳转 跳转后改变 //这会再请求一次
				//response.sendRedirect(request.getContextPath() + OVERTIME_URL);
				
				//后台跳转 不再请求了 地址栏不变
				RequestManager.forward(request, response, OVERTIME_URL);
				return;
			}
			else
			{
				request.setAttribute("session_info", sessionInfo);
				request.setAttribute("ssosession", sessionInfo.getSSOObject());
				// 公共资源.
				//把判断公共资源放在稍后的目的是为了，获取SSO中的Object
				if (isPublicUri(uri))
				{
					filterChain.doFilter(servletRequest, servletResponse);
					return;
				}
			}
			*/
			//登录后的公共资源
			if (isLoginedPublicUri(uri))//request.getContextPath()
			{
				filterChain.doFilter(servletRequest, servletResponse);
				return;
			}
			
			// 是否具有访问权限.
			if (StringUtil.isEmpty(sessionInfo.getLimitId()))
			{
				logger.debug("用户[" + sessionInfo.getLoginId() + "]没有权限, " + uri);
				request.setAttribute("msg", "没有该项权限");
				RequestManager.forward(request, response, NO_PRIVILEGE_URL);
			}
			else
			{
				FilterManager.setPrivilegePath(request,sessionInfo.getLimitId());
				filterChain.doFilter(servletRequest, servletResponse);
			}
			
		}
		catch (ServletException sx)
		{
			filterConfig.getServletContext().log(sx.getMessage());
		}
		catch (IOException iox)
		{
			filterConfig.getServletContext().log(iox.getMessage());
		}
		catch(Exception e)
		{
			request.setAttribute("errorMessage", e.getMessage());
			request.setAttribute("e", e);
			RequestManager.forward(request, response, ERROR_URL);
			return;
			
		}
	}
	public void init(FilterConfig filterConfig) throws ServletException
	{
		this.filterConfig = filterConfig;

		// 初始化登陆后的可访问资源
		ApplicationContext context = new ClassPathXmlApplicationContext(FILTER_FILE);
		LoginedResource loginedResource = (LoginedResource) context.getBean("loginedPublicResource");
		LOGINED_PUBLIC_URLS = loginedResource.getAllResource();

		LoginedResource publicResource = (LoginedResource) context.getBean("publicResource");
		PUBLIC_URLS = publicResource.getAllResource();
	}


	/**
	 * 登陆后可访问的公共url.
	 * 
	 * @param uri
	 * @return
	 */
	private boolean isLoginedPublicUri(String uri)//, String contextPath
	{
		return URLMatchUtils.isMatch(LOGINED_PUBLIC_URLS, uri);
		//String subUri = uri.substring(contextPath.length());

		//return PatternMatchUtils.simpleMatch(LOGINED_PUBLIC_URLS, subUri);
	}



	/**
	 * 未登录也允许访问的url.
	 * 
	 * @param subUrl
	 * @return
	 */
	private boolean isPublicUri(String uri)
	{
		return URLMatchUtils.isMatch(PUBLIC_URLS, uri);
	}


	// Clean up resources
	public void destroy()
	{
		this.filterConfig = null;
	}
}
